package edu.pitt.cs3530.main;

import java.io.IOException;
import java.io.PrintStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import edu.pitt.cs3530.Debug;
import edu.pitt.cs3530.identifier.HandshakeInfo;
import edu.pitt.cs3530.misc.UtilizationStatistics;
import edu.pitt.cs3530.threads.CheckUtilizationThread;
import edu.pitt.cs3530.threads.Connector;
import edu.pitt.cs3530.xml.ApplicationServerConfig;
import edu.pitt.cs3530.xml.ApplicationServerHandler;

public class ApplicationServer {
	public static void main(String args[]) throws SAXException, ParserConfigurationException, IOException {
		buildConfig(args[0]);
		if (args.length > 1) {
			if (args.length > 2) {
				Debug.Initialize(new PrintStream(args[2]));
			} else {
				Debug.Initialize(System.out);
			}
		}
		UtilizationStatistics.Initialize();
		HandshakeInfo.createHandshake();
		new CheckUtilizationThread().start();
		Connector.start();
		UtilizationStatistics.Initialize();
	}
	
	public static void buildConfig(String config) throws SAXException, ParserConfigurationException, IOException {
		XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
		ApplicationServerHandler handler = new ApplicationServerHandler();
		reader.setContentHandler(handler);
		reader.parse(config);
		ApplicationServerConfig.Initialize(handler.getConfigObject());
	}
}
